package si.yun.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import si.yun.entity.SyCourse;
import si.yun.service.SyCourseUploadService;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * @ClassName: 上传课程预览图WEB层
 * @Description: TODO
 * @Author: 柴秋生
 * @Date 2021/8/23 19:33
 */
@Controller
@RequestMapping("/uploadCourse")
@PropertySource("classpath:config.properties")
public class SyCourseUploadConreoller {
    @Autowired
    private SyCourseUploadService syCourseUploadService;
    @Value("${path1}")
    private String path2;
    /**
     * 添加课程预览图
     * @Author : 柴秋生
     * @Date : 2021/8/23 19:31
     * @Param : [session, response, files, SyCourse]
     * @Return : boolean
     */
    @RequestMapping("/uploadImg")
    @ResponseBody
    public boolean insertFiler(HttpSession session, HttpServletResponse response, @RequestParam("file") MultipartFile files, SyCourse SyCourse) throws IllegalStateException, IOException {
        //获取upload所在目录
        String realPath2=path2+ File.separator;
        //创建file
        File tempFile=new File(realPath2);
        if(tempFile.isDirectory()) {
            tempFile.mkdirs();
        }
        long currTime=System.currentTimeMillis();
        //获取后缀名
        String uniqueName = files.getOriginalFilename();
        String suffix = uniqueName.substring(uniqueName.lastIndexOf(".")+1);//截取扩展名
        //得到文件路径
        String newName=uniqueName.substring(0,uniqueName.lastIndexOf("."))+"_"+currTime+"."+suffix;
        String filePath=realPath2+File.separator+newName;
        boolean flag=false;
        SyCourse.setUrl(newName);
        //4.转存文件
        files.transferTo(new File(filePath));
        //插入数据
        int up=syCourseUploadService.insertFiler(SyCourse);
        if(up!=0) {
            flag=true;
        }else {
            flag=false;
        }
        return flag;
    }
}
